package com.cgy.utils.netx.ftp.client;

import org.apache.commons.lang3.StringUtils;

import com.cgy.utils.netx.client.INetworkClientLibrary;
import com.cgy.utils.netx.config.ClientConfig;
import com.cgy.utils.netx.ftp.utils.Sftp;
import com.google.common.base.Preconditions;

import java.io.InputStream;

/**
 * @author CHTK
 */
public class SftpClient implements INetworkClientLibrary<Sftp> {

    private Sftp sftp;

    @Override
    public INetworkClientLibrary<Sftp> initial(ClientConfig clientConfig, Object...extConfig) {
        Preconditions.checkArgument(null != clientConfig);
        Preconditions.checkArgument(StringUtils.isNotBlank(clientConfig.getUsername()));
        Preconditions.checkArgument(StringUtils.isNotBlank(clientConfig.getPassword()));
        Preconditions.checkArgument(StringUtils.isNotBlank(clientConfig.getIp()));
        Preconditions.checkArgument(clientConfig.getPort() > 0);

        this.sftp = new Sftp(clientConfig.getIp(), clientConfig.getPort(), clientConfig.getConnectionTimeoutMs(), clientConfig.getUsername(), clientConfig.getPassword());

        return this;
    }

    @Override
    public INetworkClientLibrary initial(InputStream inputStream) {
        return this;
    }

    @Override
    public INetworkClientLibrary<Sftp> connect() throws Exception {
        this.sftp.login();
        return this;
    }

    @Override
    public void release() throws Exception {
        this.sftp.logout();
    }

    @Override
    public Sftp getClient() throws Exception {
        return sftp;
    }
}
